import java.util.Arrays;
import java.util.Stack;

public class MyStack {
//    栈的底层是数组
    private int[] elem;
    private int usedSize;

    //默认容量
    final int DEFAULT_CAPACITY = 10;

    public MyStack(){
        this.elem = new int[DEFAULT_CAPACITY];
    }

    public void push(int val){
//        入 栈
        if (isFull()){
//            满了 要扩容
            elem = Arrays.copyOf(elem, elem.length * 2);
        }
        elem[usedSize] = val;
        usedSize++;
    }

    /*
     * @param :
      * @return int
     * @author: Jovak
     * @description:
     * @date: 2024/7/19 19:49
     */
    public int peek(){
//        获取栈顶元素
       if (isEmpty()){
           System.out.println("栈为空 无法获取元素!");
           throw new IllegalStateException("Stack is empty");
       }
       return elem[usedSize-1];
    }

    public int pop(){
//        取出栈顶元素
        if (isEmpty()){
            System.out.println("栈为空 无法获取元素!");
            throw new IllegalStateException("Stack is empty");
        }
        usedSize--;
        return elem[usedSize];
    }

    public boolean isFull(){
        return usedSize == elem.length;
    }

    public boolean isEmpty(){
        return usedSize == 0;
    }

    /* 括号匹配  力扣 20
     * @param s:
      * @return boolean
     * @author: Jovan
     * @description:
     * @date: 2024/7/19 19:23
     */

    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if (ch == '(' || ch == '{'|| ch == '[') {
                // 左括号入栈
                stack.push(ch);
            } else {
                // 如果是右括号，但栈为空，说明没有相匹配的左括号
                if (stack.isEmpty()) {
                    return false;
                }
                // 弹出栈顶元素，检查是否匹配
                char top = stack.pop();
                if ((ch == ')' && top != '(') ||
                        (ch == '}' && top != '{') ||
                        (ch == ']' && top != '[')) {
                    return false;
                }
            }
        }
        // 如果栈为空，则所有括号都匹配完毕；如果不为空，说明有未匹配的左括号
        return stack.isEmpty();
    }
 }

